new Vue({
    el: '#app',
    data: {
        userInfo: {
            userName: '',
            roleId: ''
        },
        fixedParkingSeats: [],
        availableSeats: [],
        searchKey: '',
        showModal: false,
        isEdit: false,
        form: {
            carId: '',
            userId: '',
            carNumber: '',
            carBrand: '',
            carModel: '',
            carColor: '',
            carType: '1',
            status: '0',
            seatNum:''
        },
        stats: {
            totalSeats: 0,
            availableSeats: 0,
            occupiedSeats: 0,
            maintenanceSeats: 0
        }
    },
    created() {
        this.loadUserInfo();
        this.loadFixedParkingSeats();
        this.loadStats();
        this. loadAvailableSeats();
    },
    methods: {
        loadUserInfo() {
            axios.get('../../userInfo')
                .then(response => {
                    if (response.data.success) {
                        this.userInfo = response.data.data;
                    }
                })
                .catch(error => {
                    console.error('Error loading user info:', error);
                });
        },
        loadAvailableSeats() {
            axios.get('/Parks/parkingSeat/getFixedAndVip')
                .then(response => {
                    if (response.data.code === 0) {
                        this.availableSeats = response.data.data;
                        console.log(response.data.data + "空闲车位");
                    } else {
                        alert(response.data.msg || '加载空闲车位失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('加载空闲车位失败');
                });
        },
        loadFixedParkingSeats() {
            axios.get('/Parks/fixedParking/list')
                .then(response => {
                    if (response.data.code === 0) {
                        this.fixedParkingSeats = response.data.data;
                        console.log(this.fixedParkingSeats);
                        this.calculateStats(this.fixedParkingSeats);
                    } else {
                        alert(response.data.msg || '加载固定车位失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('加载固定车位失败');
                });
        },
        loadStats() {
            axios.get('/Parks/fixedParking/stats')
                .then(response => {
                    if (response.data.code === 0) {
                        this.stats = response.data.data;
                    }else {
                        alert(response.data.msg || '加载统计数据失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        },
        calculateStats(seats) {
            this.stats.totalSeats = seats.length;
            this.stats.availableSeats = seats.filter(seat => seat.seatState === 0).length;
            this.stats.occupiedSeats = seats.filter(seat => seat.seatState === 1).length;
            this.stats.maintenanceSeats = seats.filter(seat => seat.seatState === 2).length;
        },
        showAddForm() {
            this.isEdit = false;
            this.form = {
                userId: '',
                carId: '',
                carNumber: '',
                carBrand: '',
                carModel: '',
                carColor: '',
                seatNum: this.availableSeats[0].seatNum,
                carType: '1',
                status: '0'
            };
            this.showModal = true;
        },
        showEditForm(seat) {
            this.isEdit = true;
            this.form = { ...seat };
            this.showModal = true;
        },
        closeModal() {
            this.showModal = false;
            this.form = {
                userId: '',
                carId: '',
                carNumber: '',
                carBrand: '',
                carModel: '',
                carColor: '',
                seatNum: '',
                carType: '1',
                status: '0'
            };
        },
        submitForm() {
            const url = this.isEdit ? 
                '/Parks/userCar/update' : 
                '/Parks/userCar/insert';
            axios.post(url, this.form)
                .then(response => {
                    if (response.data.code === 0) {
                        alert(this.isEdit ? '更新成功' : '添加成功');
                        this.closeModal();
                        this.loadFixedParkingSeats();
                        this.loadStats();
                    } else {
                        alert(response.data.msg || (this.isEdit ? '更新失败' : '添加失败'));
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert(this.isEdit ? '更新失败' : '添加失败');
                });
        },
        deleteSeat(carId) {
            if (confirm('确定要删除这辆车吗？')) {
                axios.post('/Parks/userCar/deleteById', { carId })
                    .then(response => {
                        if (response.data.code === 0) {
                            alert('删除成功');
                            this.loadFixedParkingSeats();
                        } else {
                            alert(response.data.msg || '删除失败');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('删除失败');
                    });
            }
        },
        handleSearch() {
            if (this.searchKey) {
                const results = this.fixedParkingSeats.filter(car => 
                    (car.carNumber && car.carNumber.includes(this.searchKey)) || 
                    (car.seatNum && car.seatNum.includes(this.searchKey))
                );
    
                if( results.length === 0) {
                    alert("未找到该车辆");
                    return;
                }
                this.fixedParkingSeats = results; // 更新用户列表为搜索结果
            } else {
                this.loadFixedParkingSeats(); // 如果没有搜索关键字，重新获取所有用户
            }
        },


               // 获取车辆类型文本
               getCarType(type) {
                const typeMap = {
                    1: '固定车辆',
                    2: 'VIP车辆',
                    3: '临时车辆'
                };
                return typeMap[type] || '未知';
            },
        // 获取状态样式类
        getStatusClass(status) {
            const statusMap = {
                0: 'status-normal',
                1: 'status-disabled'
            };
            return statusMap[status] || '';
        },
        // 获取状态文本
        getStatusText(status) {
            const statusMap = {
                0: '正常',
                1: '禁用'
            };
            return statusMap[status] || '未知';
        },

         // 退出登录
         handleLogout() {
            axios.post('/Parks/logout')
                .then(() => {
                    sessionStorage.removeItem('userInfo');
                    window.location.href = '../../login.html';
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('退出失败');
                });
        }
    }, 
});